<template>
  <div class="user-profile-container">
    <el-card class="profile-card" shadow="hover" v-loading="loading">
      <div v-if="error" class="error-message">
        <el-alert :title="error" type="error" show-icon />
        <el-button @click="refreshUserData" type="primary" style="margin-top: 10px">
          重新加载
        </el-button>
      </div>
      
      <div v-else>
        <div class="profile-header">
          <h2>用户个人信息</h2>
          <div class="vip-banner" :class="{'non-vip': !membershipInfo}">
            <span class="vip-level" v-if="membershipInfo">
              {{ membershipInfo.membershipType || 'VIP' }}
            </span>
            <span class="vip-expire" v-if="membershipInfo && membershipInfo.expireTime">
              到期: {{ formatDate(membershipInfo.expireTime) }}
            </span>
            <span class="non-vip-text" v-else>您当前还不是VIP</span>
            <span class="upgrade-prompt" v-if="!membershipInfo">尽快充值成为VIP吧</span>
          </div>
        </div>

        <!-- 用户核心信息 -->
        <div class="user-core">
          <el-avatar :size="100" :src="userInfo.avatarUrl" class="user-avatar" />
          <div class="user-identity">
            <h3>{{ userInfo.nickname || userInfo.username }}</h3>
            <p class="email">{{ userInfo.email }}</p>
          </div>
        </div>

        <!-- 社交数据 -->
        <div class="social-data">
          <div class="data-item">
            <div class="data-value">{{ statisticsInfo.collectionCount }}</div>
            <div class="data-label">收藏</div>
          </div>
          <div class="data-item">
            <div class="data-value">{{ statisticsInfo.followingCount }}</div>
            <div class="data-label">关注</div>
          </div>
          <div class="data-item">
            <div class="data-value">{{ statisticsInfo.followerCount }}</div>
            <div class="data-label">粉丝</div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="basic-info">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">用户ID</span>
              <span class="info-value">{{ userInfo.userId }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">等级</span>
              <span class="info-value">
                {{ levelInfo.levelName || 'LV0' }}
                (经验: {{ levelInfo.currentExp }}/{{ levelInfo.requiredExp }})
              </span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">手机号</span>
              <span class="info-value">{{ userInfo.phone || '--' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">昵称</span>
              <span class="info-value">{{ userInfo.nickname || '--' }}</span>
            </div>
          </div>
        </div>

        <!-- 个人资料 -->
        <div class="profile-section">
          <div class="profile-item">
            <span class="profile-label">性别</span>
            <span class="profile-value">{{ formatGender(userInfo.gender) }}</span>
          </div>
          <div class="profile-item">
            <span class="profile-label">爱好</span>
            <span class="profile-value">
              <template v-if="userInfo.hobby && userInfo.hobby !== '未设置'">
                <el-tag size="small" class="hobby-tag">{{ userInfo.hobby }}</el-tag>
              </template>
              <span v-else>未设置</span>
            </span>
          </div>
          <div class="profile-item bio-item">
            <span class="profile-label">个人介绍</span>
            <span class="profile-value">{{ userInfo.introduction || '这个人很懒，什么都没留下~' }}</span>
          </div>
        </div>

        <div class="action-buttons">
          <el-button
            type="primary"
            @click="showEditDialog = true"
            icon="el-icon-edit"
            class="edit-btn"
            round
          >
            编辑资料
          </el-button>
        </div>

        <!-- 编辑资料弹窗 -->
        <el-dialog title="编辑资料" v-model="showEditDialog" width="30%">
          <el-form :model="editForm" ref="editForm" :loading="updating">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="2"></el-option>
                <el-option label="保密" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="爱好">
              <el-input v-model="editForm.hobby" placeholder="请输入爱好"></el-input>
            </el-form-item>
            <el-form-item label="个人介绍">
              <el-input
                type="textarea"
                v-model="editForm.introduction"
                :rows="3"
                placeholder="请输入个人介绍"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showEditDialog = false">取消</el-button>
            <el-button type="primary" @click="updateProfile" :loading="updating">保存</el-button>
          </template>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { useUserStore } from '@/stores/user'
import { computed, ref, onMounted, onActivated, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserProfile',
  setup() {
    const userStore = useUserStore()
    
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const showEditDialog = ref(false)
    const updating = ref(false)
    const editForm = ref({
      username: '',
      email: '',
      gender: 0,
      hobby: '',
      introduction: ''
    })

    // 计算属性 - 直接使用store中的数据
    const userInfo = computed(() => userStore.userInfo)
    const levelInfo = computed(() => userStore.levelInfo)
    const membershipInfo = computed(() => userStore.membershipInfo)
    const statisticsInfo = computed(() => userStore.statisticsInfo)

    // 刷新用户数据
    const refreshUserData = async () => {
      if (!userStore.isLoggedIn) {
        error.value = '用户未登录，请先登录'
        return
      }

      loading.value = true
      error.value = ''
      
      try {
        console.log('开始刷新用户数据...')
        await userStore.fetchUserDetail()
        console.log('用户数据刷新成功')
        // 更新编辑表单数据
        updateEditForm()
      } catch (err) {
        error.value = '获取用户信息失败: ' + (err.message || '未知错误')
        console.error('获取用户详情失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 更新编辑表单数据
    const updateEditForm = () => {
      editForm.value = {
        username: userInfo.value.username || '',
        email: userInfo.value.email || '',
        gender: userInfo.value.gender ?? 0,
        hobby: userInfo.value.hobby || '',
        introduction: userInfo.value.introduction || ''
      }
    }

    // 更新用户资料
    const updateProfile = async () => {
      updating.value = true
      try {
        const updateData = { ...editForm.value }
        const userId = userInfo.value.userId
        
        if (!userId) {
          ElMessage.error('用户ID不存在，无法更新资料')
          return
        }
        
        // 调用修正后的方法名
        const response = await userStore.updateUserInfo(userId, updateData)
        
        if (response && response.code === 200) {
          ElMessage.success('资料更新成功')
          await refreshUserData() // 刷新数据
          showEditDialog.value = false
        } else {
          ElMessage.error(response?.message || '更新失败')
        }
      } catch (err) {
        ElMessage.error(
          err.response?.data?.message
            ? `更新失败: ${err.response.data.message}`
            : '网络连接异常，请稍后重试'
        )
      } finally {
        updating.value = false
      }
    }

    // 格式化日期
    const formatDate = (dateValue) => {
      if (!dateValue) return '--'
      const date = typeof dateValue === 'number' ? new Date(dateValue) : new Date(dateValue)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    }

    // 格式化性别
    const formatGender = (gender) => {
      if (gender === 1) return '男'
      if (gender === 2) return '女'
      return '保密'
    }

    // 监听登录状态变化
    watch(() => userStore.isLoggedIn, (newValue) => {
      if (newValue && userStore.getUserId()) {
        console.log('检测到用户登录，刷新数据')
        refreshUserData()
      }
    })

    // 生命周期钩子
    onMounted(() => {
      console.log('UserProfile 组件已挂载')
      console.log('登录状态:', userStore.isLoggedIn)
      console.log('用户ID:', userStore.getUserId())
      if (userStore.isLoggedIn) {
        refreshUserData()
      } else {
        error.value = '请先登录后查看个人信息'
      }
    })

    onActivated(() => {
      // 当使用keep-alive缓存组件时，每次激活都刷新数据
      console.log('UserProfile 组件已激活')
      if (userStore.isLoggedIn) {
        refreshUserData()
      }
    })

    return {
      // 响应式数据
      loading,
      error,
      showEditDialog,
      updating,
      editForm,
      
      // 计算属性
      userInfo,
      levelInfo,
      membershipInfo,
      statisticsInfo,
      
      // 方法
      refreshUserData,
      updateProfile,
      formatDate,
      formatGender
    }
  }
}
</script>

<style scoped>
.user-profile-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 20px;
}

.profile-card {
  border-radius: 16px;
  padding: 30px;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: none;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6d9ff;
}

.profile-header h2 {
  font-size: 22px;
  color: #6a3093;
  margin: 0;
  font-weight: 600;
}

.vip-banner {
  background: linear-gradient(45deg, #9c27b0, #ffd700);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 13px;
  display: flex;
  align-items: center;
}

.vip-level {
  font-weight: bold;
  margin-right: 5px;
}

.vip-expire {
  font-size: 12px;
  opacity: 0.9;
}

/* 非VIP状态样式 */
.vip-banner.non-vip {
  background: #f0f0f0;
  color: #666;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px 15px;
}

.non-vip-text {
  font-weight: bold;
  font-size: 14px;
}

.upgrade-prompt {
  font-size: 12px;
  color: #888;
}

.user-core {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar {
  border: 3px solid #ffffff;  /* 将边框颜色改为白色 */
  box-shadow: 0 4px 12px rgba(156, 39, 176, 0.15); /* 可保留或调整阴影 */
}

.user-identity {
  margin-left: 20px;
}

.user-identity h3 {
  font-size: 20px;
  color: #4a2c82;
  margin: 0 0 5px 0;
}

.email {
  color: #7e57c2;
  font-size: 14px;
  margin: 0;
}

.social-data {
  display: flex;
  justify-content: space-around;
  margin: 25px 0;
  padding: 15px 0;
  background: rgba(214, 204, 234, 0.3);
  border-radius: 12px;
}

.data-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.data-item:hover {
  transform: translateY(-3px);
}

.data-value {
  font-size: 20px;
  font-weight: bold;
  color: #6a3093;
}

.data-label {
  font-size: 14px;
  color: #7e57c2;
  margin-top: 5px;
}

.basic-info {
  background: #ffffff;  /* 浅灰色背景 */
  border-radius: 8px;    /* 圆角 */
  padding: 15px;         /* 内边距 */
  margin-bottom: 15px;   /* 底部外边距 */
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  padding: 0 10px;
}

.info-label {
  display: block;
  font-size: 13px;
  color: #7e57c2;
  margin-bottom: 3px;
}

.info-value {
  font-size: 15px;
  color: #4a2c82;
  font-weight: 500;
}

.profile-section {
  background: #ffffff;   /* 浅灰色背景 */
  border-radius: 8px;    /* 圆角 */
  padding: 15px;         /* 内边距 */
}

.profile-item {
  display: flex;
  margin-bottom: 15px;
}

.profile-item:last-child {
  margin-bottom: 0;
}

.bio-item {
  align-items: flex-start;
}

.profile-label {
  width: 80px;
  font-size: 14px;
  color: #7e57c2;
  font-weight: 500;
}

.profile-value {
  flex: 1;
  font-size: 14px;
  color: #4a2c82;
  line-height: 1.5;
}

.hobby-tag {
  background: #d1c4e9;
  color: #4a2c82;
  border: none;
  margin-right: 8px;
  margin-bottom: 8px;
}

.action-buttons {
  text-align: center;
  margin-top: 25px;
}

.edit-btn {
  background: #f0f0f0; /* 浅灰色背景 */
  color: #666; /* 深灰色文字 */
  border: 1px solid #e0e0e0; /* 浅灰色边框 */
  padding: 10px 25px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); /* 轻微阴影 */
}

.edit-btn:hover {
  background: #e0e0e0; /* 悬停时稍深一点的灰色 */
  color: #555;
}

.error-message {
  text-align: center;
  padding: 20px;
}
</style>